package infra.starters;



import java.util.Vector;

import processing.core.*;
import org.NooLab.utilities.logging.PrintLog;



import org.NooLab.glue.components.*;
import org.NooLab.glue.components.pkg.TaskPackage;
import org.NooLab.glue.instances.*;
import org.NooLab.glue.subscription.FilterPackageIntf;
 
 
 
import infra.common.DataContainer;
import infra.common.FilterExample;
 



public class MsgSourceInstance extends PApplet {
	
	private static final long serialVersionUID = -6009042607634506822L;

	
	SrcInstance srcInstance;
	 
	
	public void setup(){
		 
		
		background( 188,208,188);
		// start this in its own thread...
		srcInstance = new SrcInstance();
		
	}
	
	
	
	public void draw(){
		 
	}
 



	public void keyPressed() {
		 
		if (key=='s'){
			srcInstance.prepareData() ;
			srcInstance.getInstance().send() ;
		}
		

		if (key=='r'){
			srcInstance.getInstance().connect() ;
		}
		if (key=='u'){
			srcInstance.getInstance().disconnect() ;
		}

		if ((key=='q') || (key=='d')){
			srcInstance.cancelTask() ;
		}
		
		if (key=='x'){
			if (srcInstance!=null){
				srcInstance.getInstance().disconnect();
			}
			System.exit(0);
		}
	}
}


/**
 * 
 * TODO   accepting slowdown and sleep messages issued by Receptors 
 * 		  this is kind of an "afferent" fiber if we take receptors as more
 *        central instance than the sources ... sources could represent any kind of sensory!  
 * 
 */
class SrcInstance implements Runnable, ResultReceiverIntf{ 

	// 
	ParticipantFactory factory ;
	MessageBoardFactoryProperties factoryProperties ;
	ParticipantSourceIntf participant ;
	 
	FilterExample filter;
	
	// helper objects
	Thread iThrd; 
	PrintLog out = new PrintLog(2,false);
	
	
	public SrcInstance(){
		// we start then instance into a thread, which is independent from the PApplet
		(new Thread(this,"SrcInstance-main")).start() ;
	}	 
		
	public void run() {
		 create();
	}

	private void create(){
		 
		try{
			factoryProperties = new MessageBoardFactoryProperties()  ;
			
			factoryProperties.setHomePath( "D:/dev/java/data/test/mb/" ) ;
			factoryProperties.setProtocolId( MessageBoardFactoryProperties.protocolUDP ) ;
			factoryProperties.setProtocolId( MessageBoardFactoryProperties.protocolTCP ) ;
			factoryProperties.setProtocolId(MessageBoardFactoryProperties.protocolHREST);
			
			factoryProperties.setRemoteInstancesFlag( false ) ; // false: only local addresses
			factoryProperties.setTypeOfInstance( MessageBoardFactoryProperties.variant_SOURCE );  
			
			filter = new FilterExample(); 
			factoryProperties.setFilter((FilterPackageIntf) filter) ;

			
			// ------------------------------------------------------------
			factory = new ParticipantFactory( factoryProperties , this ) ;

			factory.config().setActiveReceiptsExchange( true ) ;
			factory.config().setInstanceAsUnique( true ) ; // only 1 instance of this type (here receptor) will be registered (even for http clients) 
			factory.config().setName( "testSource0") ;
			factory.config().setDefaultDocType("doc,*") ;
			
			participant = (ParticipantSourceIntf)(factory.getInstance()) ;
			
			
			
			// setContentType("doc");
			participant.connect() ;
			
			// participant.connectTo() ;
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
	  
	// =============== local methods ===============
	// this is used by the application object, which is hosting this instance (linkage to GUI) 
	public ParticipantSourceIntf getInstance(){
		return participant;
	}

	public void cancelTask(){
		int cancelState;
		/*
		 *    canceling a task needs a transactionID,
		 *    if none is given, the last activated one will be chosen 
		 *    (acc. to option in factoryProperties, factory.config() ) 
		 */
		
		cancelState = participant.cancelTask();
		
		if (cancelState<0){
			// failure of canceling ;
		}
	}
	
	
	public void prepareData(){

		TaskPackage taskPackage;
		
		
		String filename, contentType = "rawdata";

		contentType = "doc" ;
		DataContainer dataobj=new DataContainer() ;
		
		// creating a TaskPackage
		// taskPackage = getNewTaskPackage() ; if no parameters are provided we have to define them separately
		
		 
		taskPackage = factory.getTaskPackage( contentType ) ;
		// note, that in case of UDP ONLY references should be transmitted
		
		filename = "D:/dev/java/data/texter/data/out/textmapdata_00007.txt"+" - 123";
		
		// the taskPackage may contain ANY kind of object, ...there are slots for primitive types
		taskPackage.getNums().add(99 ) ;
		taskPackage.setDataString( filename) ;
		
		// any user-based object format, of course, 
		dataobj.setObjFromFile(filename) ; // e.g. reading the file and representing it as byte[]
		// note, that in case of UDP ONLY references should be transmitted, 
		// no objects should be used, since it is not predictable, if and where the (physical) router
		// will truncate the message
		taskPackage.setData(dataobj, "dataobj");
		
		taskPackage.setTypeOfProceedings("task"); // task = expects some kind of result,
		 							  // "travel" = one way pass through, no results will be returned
		
		participant.setTask(taskPackage);
	}
	
	
	// =============== interfaced methods ===============
	
	// finally, here we will find the results 
	public void resultsProvider(TaskPackage resultpackage) {
		 
		long tid ;
		
		out.printErr(2, "MsgSourceInstance :: SrcInstance :: resultsProvider()");
		
		tid = resultpackage.getTransactionID();
		
		
	}

	@Override
	public void currentStateMessage(String str) {
		
		out.printErr(4, "MsgSourceInstance :: SrcInstance :: currentStateMessage()");
		out.print(2,"Simple State Message : "+str);
		
	}

	@Override
	public void resultsProvider(Vector<TaskPackage> resultpackages) {
		// TODO Auto-generated method stub
		
	}

	 

	  

}
 
  
 
